package com.ecnu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.system.domain.Project;
import com.ecnu.system.domain.ProjectTeacher;
import com.ecnu.system.domain.ProjectUserEvaluate;
import com.ecnu.system.domain.dto.EvaluateDTO;
import com.ecnu.system.domain.vo.EvaluateVO;
import com.ecnu.system.domain.vo.EvaluatesVO;
import com.ecnu.system.domain.vo.StageVO;
import com.ecnu.system.mapper.ProjectMapper;
import com.ecnu.system.mapper.ProjectTeacherMapper;
import com.ecnu.system.mapper.ProjectUserEvaluateMapper;
import com.ecnu.system.service.IProjectUserEvaluateService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProjectUserEvaluateServiceImpl
        extends ServiceImpl<ProjectUserEvaluateMapper, ProjectUserEvaluate>
        implements IProjectUserEvaluateService {
    @Autowired
    private ProjectUserEvaluateMapper userEvaluateMapper;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private ProjectTeacherMapper teacherMapper;

    @Override
    public EvaluateVO getStageList(String projectId, String userId, List<StageVO> copy) {
        //取对应活动、人员的分数数据
        ProjectUserEvaluate one = userEvaluateMapper.selectOne(new QueryWrapper<ProjectUserEvaluate>()
                .eq("pro_id", projectId)
                .eq("user_id", userId));
        EvaluateVO evaluateVO = new EvaluateVO();
        if (one != null && one.getScore() != null) {
            //写入评价
            evaluateVO.setEvaluate(StringUtils.isBlank(one.getEvaluate())? "" : one.getEvaluate());
            ObjectMapper objectMapper = new ObjectMapper();
            //分数结构处理
            List<EvaluatesVO> checkDTOs = ((List<Map<String, Object>>) getList(one.getScore()))
                    .stream()
                    .map(map -> objectMapper.convertValue(map, EvaluatesVO.class))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(checkDTOs)) {
                //获取分数
                Map<String, String> scoreMap = checkDTOs.stream()
                        .collect(Collectors.toMap(EvaluatesVO::getId, EvaluatesVO::getScore));
                Integer count = 0;
                //设置分数
                for (StageVO stageVO : copy) {
                    String s = scoreMap.get(stageVO.getId());
                    s=StringUtils.isNotBlank(s)? s:"0";
                    Integer score =Integer.valueOf( s);
                    if (score != null) {
                        stageVO.setScore(String.valueOf(score));
                        count += score;
                    } else {
                        count += 0;
                    }

                }
                //计算总分
                StageVO stageVO = new StageVO();
                stageVO.setId("last");
                stageVO.setMissionName("终评");
                stageVO.setScore(String.valueOf(count == 0 ? 0 : count / copy.size()));
                copy.add(stageVO);
            } else {
                StageVO stageVO = new StageVO();
                stageVO.setId("last");
                stageVO.setMissionName("终评");
//                stageVO.setScore(0);
                copy.add(stageVO);
            }
        } else {
            StageVO stageVO = new StageVO();
            stageVO.setId("last");
            stageVO.setMissionName("终评");
//            stageVO.setScore(0);
            copy.add(stageVO);
            evaluateVO.setEvaluate( "");
        }
        evaluateVO.setStageList(copy);
        return evaluateVO;
    }

    @Override
    public AjaxResult addEvaluate(EvaluateDTO dto, LoginUser loginUser) throws JsonProcessingException {
        Project project = projectMapper.selectById(dto.getProjectId());
        if (project == null) {
            return AjaxResult.error("活动不存在");
        }
        LambdaQueryWrapper<ProjectTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectTeacher::getProId, dto.getProjectId());
        wrapper.eq(ProjectTeacher::getTechId, loginUser.getUserId());
        List<ProjectTeacher> projectTeachers = teacherMapper.selectList(wrapper);

        boolean isUnauthorizedRole = loginUser.getUser().getRoles().stream()
                .noneMatch(role -> role.getRoleId() != 1L && role.getRoleId() != 2L);
        if ((projectTeachers == null || projectTeachers.isEmpty()) && !isUnauthorizedRole &&
                !project.getCreateUser().equals(String.valueOf(loginUser.getUserId()))) {
            return AjaxResult.error("您没有权限执行该操作，如需提交请联系管理员或活动负责人调整");
        }
        userEvaluateMapper.delete(new QueryWrapper<ProjectUserEvaluate>().eq("pro_id", dto.getProjectId())
                .eq("user_id", dto.getUserId()));
        ProjectUserEvaluate evaluate = new ProjectUserEvaluate();
        evaluate.setProId(dto.getProjectId());
        evaluate.setUserId(dto.getUserId());
        ObjectMapper objectMapper = new ObjectMapper();
        evaluate.setScore(dto.getEvaList() == null ? "[]" : objectMapper.writeValueAsString(dto.getEvaList()));
        evaluate.setEvaluate(dto.getEvaluate());
        userEvaluateMapper.insert(evaluate);
        return AjaxResult.success();
    }

    /**
     * string ==> object(json方式的）
     *
     * @param mission
     * @return
     */
    private Object getList(String mission) {
        List<Map> checkLists = new ArrayList<>();
        if (StringUtils.isNotBlank(mission)) {
            try {
                mission = mission
                        .replaceAll("^\"+", "")  // 去除开头引号
                        .replaceAll("\"+$", "")
                        .replaceAll("^\"|\"$", "")
                        .replaceAll("\\\\\"", "\"")
                        .replaceAll("\\\\\\\\", "\\\\");
                checkLists = new ObjectMapper().readValue(mission, List.class);
            } catch (JsonProcessingException e) {
                return mission;
            }
        }
        return checkLists;
    }
}
